#include "delay.h"
#include "stm32f4xx.h"
#include "board.h"



#define  DWT_CYCCNT  *(volatile unsigned int *)0xE0001004 /* Cycle Count Register*/
#define  DWT_CR      *(volatile unsigned int *)0xE0001000 /* Control Register*/
#define  DEM_CR      *(volatile unsigned int *)0xE000EDFC /* Debug Exception and Monitor Control Register*/

#define  DEM_CR_TRCENA               (1 << 24)
#define  DWT_CR_CYCCNTENA            (1 <<  0)

/**
  * @brief  This is the initialization function of the cortex DWT register to enable the DWT function.
  * @param  None
  * @retval None
  */
int rt_hw_cortex_dwt_init(void)
{
    DEM_CR         |= (unsigned int)DEM_CR_TRCENA;   /* Enable Cortex-M4's DWT CYCCNT reg.  */
    DWT_CYCCNT      = (unsigned int)0u;              /* Reset*/
    DWT_CR         |= (unsigned int)DWT_CR_CYCCNTENA;/* 忽略所有位*/
    return 0;
}
INIT_BOARD_EXPORT(rt_hw_cortex_dwt_init);
/**
  * @brief  This is a us delay function.
  * @param  delay time
  * @retval None
  */
void delay_us(unsigned int _ulDelayTime)
{
    unsigned int tCnt, tDelayCnt;
    unsigned int tStart;

    tStart = DWT_CYCCNT;                                     /* 获取刚进入时计数寄存器的值 */
    tCnt = 0;
    tDelayCnt = _ulDelayTime * (SystemCoreClock / 1000000);  /* 计算所需要的节拍数1us=_ulDelayTime*168 */

    while (tCnt < tDelayCnt) /* 如果计数器的值>= 需要等待的节拍数*/
    {
        tCnt = DWT_CYCCNT - tStart; /* 求减过程中如发生一次计数器重新计数,依然可以正确计数 */
    }
}
/**
  * @brief  This is a ms delay function.
  * @param  delay time
  * @retval None
  */
void delay_ms(unsigned int _ulDelayTime)
{
    delay_us(1000 * _ulDelayTime);
}
